/**
 * HttpTask.java
 * 
 * Created on 26.05.2012 15:54:00
 */
package de.g18.scavengerhunt.types;

import java.util.HashMap;
import java.util.Map;

import android.os.AsyncTask;
import de.g18.scavengerhunt.utils.HttpUtil;

/**
 * Task to perform request against the webservice
 */
public class HttpTask extends AsyncTask<Object, Integer, String> {

    private HttpUtil httpUtility = null;

    private boolean  isSuccess  = true;

    @Override
    protected String doInBackground(Object... params) {
        String response = null;
        String url = (String) params[0];
        String method = (String) params[1];

        httpUtility = new HttpUtil(url);
        if ((method.equals("POST") || method.equals("DELETE")) && params.length > 2) {
            @SuppressWarnings("unchecked") // we know, what we've put in the map... so don't panic
            Map<String, Object> paramMap = (HashMap<String, Object>) params[2];
            for (String paramKey : paramMap.keySet()) {
                httpUtility.addParameter(paramKey, (String) paramMap.get(paramKey));
            }
        }

        try {
            response = httpUtility.executeRequest(method);
        } catch (HttpResourceNotFoundException e) {
            isSuccess = false;
            return null;
        }
        isSuccess = response ==null ? false : true;
        return response;
    }

    /**
     * Indicates if the task was completed successfully.
     *  will only return correct values if the task has been executed
     */
    public boolean isSuccess() {
        return isSuccess;
    }
}
